import * as types from './mutation-types'
import business from '../../api/business'
import * as gtypes from '../../mutation-types'
import {getCache} from '../../actions'
import {getCacheByKey, deepClone} from '@/utils/m7Utils'
import {getDicFromField} from '@/utils/workflowUtils'
import http from '../../api/http'
// import send from "../../api/http"
/**
 * 刷新工作台业务待处理数
 */
export const refreshUndealNum = ({commit}) => {
  return business.refreshUndealNum({})
    .then(
      response => {
        if (response.success) {
          commit(types.REFRESH_BUSINESS_UNDEALNUM, {roleNum: response.roleNum, total: response.total, noReadNum: response.noReadNum})
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const readBusiness = ({commit}, data) => {
  return business.readBusiness(data)
    .then(
      response => {
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 待领取工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.createUser 高级查询中，创建人
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getRoleUnDealBusiness = ({commit}, data) => {
  return business.getRoleUnDealBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_ROLE_UNDEAL_BUSINESS, {list: response.list, more: response.more, count: response.count, businessTime: response.businessTime})
          } else {
            commit(types.GET_ROLE_UNDEAL_BUSINESS, {list: response.list, count: response.count, businessTime: response.businessTime})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getBusinessCount = ({commit}, data) => {
  return business.getBusinessCount(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getRoleUnDealBusinessCount = ({commit}, data) => {
  return business.getRoleUnDealBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 我的待办工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.createUser 高级查询中，创建人
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getUnDealBusiness = ({commit}, data) => {
  return business.getUnDealBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_UNDEAL_BUSINESS, {list: response.list, more: response.more, count: response.count, businessTime: response.businessTime})
          } else {
            commit(types.GET_UNDEAL_BUSINESS, {list: response.list, count: response.count, businessTime: response.businessTime})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getUnDealBusinessCount = ({commit}, data) => {
  return business.getUnDealBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 我创建的工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.createUser 高级查询中，创建人
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getAssignedBusiness = ({commit}, data) => {
  return business.getAssignedBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_ASSIGNED_BUSINESS, {list: response.list, more: response.more, count: response.count})
          } else {
            commit(types.GET_ASSIGNED_BUSINESS, {list: response.list, count: response.count})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getAssignedBusinessCount = ({commit}, data) => {
  return business.getAssignedBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 我参入的工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.createUser 高级查询中，创建人
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getFollowedBusiness = ({commit}, data) => {
  return business.getFollowedBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_FOLLOWED_BUSINESS, {list: response.list, more: response.more, count: response.count})
          } else {
            commit(types.GET_FOLLOWED_BUSINESS, {list: response.list, count: response.count})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getFollowedBusinessCount = ({commit}, data) => {
  return business.getFollowedBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 全部的工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.master 当前处理人同事（座席id）
 * @param {String} data.ownerdep 当前处理人部门（部门id）
 * @param {String} data.ownercom 当前处理人常用：我自己、我的我的下属、我的部门、我和我的下级部门
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const queryAllBusiness = ({commit}, data) => {
  return business.queryAllBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (Object.keys(data).length === 1 && data.number) {
            return response
          } else {
            if (response.more) {
              commit(types.QUERY_ALL_BUSINESS, {list: response.list, more: response.more, count: response.count})
            } else {
              commit(types.QUERY_ALL_BUSINESS, {list: response.list, count: response.count})
            }
            commit(types.SET_BUSINESS_CONDITION, response.condition)
            return response
          }
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const queryAllBusinessCount = ({commit}, data) => {
  return business.queryAllBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 全部的待办工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.master 当前处理人同事（座席id）
 * @param {String} data.ownerdep 当前处理人部门（部门id）
 * @param {String} data.ownercom 当前处理人常用：我自己、我的我的下属、我的部门、我和我的下级部门
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getAllUncompleteBusiness = ({commit}, data) => {
  return business.getAllUncompleteBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_ALL_UNCOMPLETE_BUSINESS, {list: response.list, more: response.more, count: response.count})
          } else {
            commit(types.GET_ALL_UNCOMPLETE_BUSINESS, {list: response.list, count: response.count})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getAllUncompleteBusinessCount = ({commit}, data) => {
  return business.getAllUncompleteBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 全部完成的工单查询
 * @param {Object} data
 * @param {String} data.flow 工单类型
 * @param {Number} data.page 第几页
 * @param {Number} data.limt 一页多少行
 * @param {String} data.query 客户名称
 * @param {String} data.ownercomCreateUser 高级查询中，创建人，所属者
 * @param {String} data.master 当前处理人同事（座席id）
 * @param {String} data.ownerdep 当前处理人部门（部门id）
 * @param {String} data.ownercom 当前处理人常用：我自己、我的我的下属、我的部门、我和我的下级部门
 * @param {String} data.step 高级查询中，工单步骤
 * @param {String} data.number 高级查询中，工单编号
 * @param {String} data.createTime$begin 高级查询中，创建时间开始时间
 * @param {String} data.createTime$end 高级查询中，创建时间结束时间
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 高级查询中，查询工单字段的内容
 */
export const getAllFinishedBusiness = ({commit}, data) => {
  return business.getAllFinishedBusiness(data)
    .then(
      response => {
        if (response.success) {
          if (response.more) {
            commit(types.GET_ALL_FINISHED_BUSINESS, {list: response.list, more: response.more, count: response.count})
          } else {
            commit(types.GET_ALL_FINISHED_BUSINESS, {list: response.list, count: response.count})
          }
          commit(types.SET_BUSINESS_CONDITION, response.condition)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getAllFinishedBusinessCount = ({commit}, data) => {
  return business.getAllFinishedBusiness(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 工单保存
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {String} data.flow 工单类型
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 工单字段
 * @param {String} data.nextAction 下一步处理动作
 * @param {String} data.nextUser 下一步处理人
 */
export const addBusinessTask = ({commit, rootState}, data) => {
  let message = deepClone(data)
  if (message.followedAgents && message.followedAgents.length === 0) {
    delete message.followedAgents
  }
  return processBusinessData({commit, rootState}, message).then((res) => {
    return business.addBusinessTask(res)
      .then(
        response => {
          if (response.success) {
            window.localStorage.businessTypeDefault = response.data.flow
            return businessData({commit, rootState}, response.data).then((data) => {
              commit(types.SET_BUSINESS_ACTION, data)
              commit(gtypes.SET_SUCCESS, 'business.addbusinessSuccess')
              return data._id
            })
          } else if (response.errorCode === '403') {
            commit(gtypes.SET_ERROR, 'businessChangeError')
          } else {
            commit(gtypes.SET_ERROR, 'operationFail')
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 工单暂存
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {String} data.flow 工单类型
 * @param {String} data.d38a19e0-c5af-11e5-a307-19b0da236bee 工单字段
 * @param {String} data.nextAction 下一步处理动作
 * @param {String} data.nextUser 下一步处理人
 * @param {String} data.customer 客户id
 * @param {String} data.callId 通话id
 */
export const addTempBusinessTask = ({commit, rootState}, data) => {
  // 暂存工单不提交动作信息
  delete data.actionFields
  return processBusinessData({commit, rootState}, data).then((res) => {
    return business.addTempBusinessTask(res)
      .then(
        response => {
          if (response.success) {
            return businessData({commit, rootState}, response.data).then((data) => {
              commit(types.SET_BUSINESS_ACTION, data)
              commit(gtypes.SET_SUCCESS, 'business.businessTempSuccess')
              return data._id
            })
          } else {
            commit(gtypes.SET_ERROR, 'business.businessTempFail')
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 根据id获取工单详细信息
 * @param {Object} data
 * @param {String} data._id 工单id
 */
export const getBusinessDetailById = ({commit, rootState}, data, tag) => {
  return business.getBusinessDetailById(data)
      .then(
        response => {
          if (response.success) {
            return businessData({commit, rootState}, response.data).then((data) => {
              commit(types.SET_BUSINESS_ACTION, data)
              return data
            })
          }
        }
      ).catch((err) => {
        console.log(err)
        // 'message.default_tips'
      })
}
/**
 * 添加工单备注
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Number} data.backInfo 退回原因
 */
export const addBusinessBackInfo = ({commit}, data) => {
  return business.addBusinessBackInfo(data)
    .then(
      response => {
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 变更当前处理人
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Number} data.master 变更的处理人
 */
export const changeBusinessMaster = ({commit}, data) => {
  return business.changeBusinessMaster(data)
    .then(
      response => {
        if (!response.success) {
          commit(gtypes.SET_ERROR, 'message.operationFail')
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 变更当前处理人
 * @param {String} _id 工单id
 */
export const setTaskToMe = ({commit, rootState}, data) => {
  let req = {}
  req._id = data
  req.master = rootState.session.user._id
  return business.setTaskToMe(req)
    .then(
      response => {
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 执行工单动作
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Number} data.master 领取座席
 * @param {Number} data.actionId 动作id
 */
export const excuteBusinessStepAction = ({commit, rootState}, data) => {
  return processBusinessData({commit, rootState}, data).then((res) => {
    return business.excuteBusinessStepAction(res)
      .then(
        response => {
          if (response.success) {
            return businessData({commit, rootState}, response.data).then((data) => {
              commit(types.SET_BUSINESS_ACTION, data)
            })
          } else if (response.errorCode === '403') {
            commit(gtypes.SET_ERROR, 'businessChangeError')
          } else {
            commit(gtypes.SET_ERROR, response.message || 'message.handleFlowFail')
          }
          return response.data
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 工单动作某一步的暂存
 */
export const saveTempStepInfo = ({commit}, data) => {
  return business.saveTempStepInfo(data)
    .then(
      response => {
        if (!response.success) {
          // commit(gtypes.SET_ERROR, 'message.operationFail')
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 工单退回
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Number} data.master 领取座席
 * @param {Number} data.actionId 动作id
 */
export const excuteBusinessBackAction = ({commit, rootState}, data) => {
  return processBusinessData({commit, rootState}, data).then((res) => {
    return business.excuteBusinessBackAction(res)
      .then(
        response => {
          if (response.success) {
            return businessData({commit, rootState}, response.data).then((data) => {
              commit(types.SET_BUSINESS_ACTION, data)
            })
          } else if (response.errorCode === '403') {
            commit(gtypes.SET_ERROR, 'businessChangeError')
          } else {
            commit(gtypes.SET_ERROR, response.message || 'message.handleFlowFail')
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 工单附件删除
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Number} data.fileId 字段id
 * @param {Number} data.fileId 附件id
 */
export const delBusAttach = ({commit}, data) => {
  return new Promise(function (resolve) {
    business.delBusAttach(data)
      .then(
        response => {
          if (response.success) {
            resolve()
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 删除工单
 * @param {Object} data
 * @param {Object} data._id 工单id集合 {$in:[]}
 */
export const deleteBusiness = ({commit}, data) => {
  return business.deleteBusiness(data)
    .then(
      response => {
        if (response.success) {
          commit(types.DELETE_BUSINESS, true)
        } else {
          commit(gtypes.SET_ERROR, response.message || 'message.delDataFail')
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 获取客户的最后一次工单信息
 * @param {Object} data
 * @param {String} data.customer 客户id
 */
export const getCustomerHistoryBusiness = ({commit, rootState}, {data, type}) => {
  return business.getCustomerHistoryBusiness(data)
    .then(
      response => {
        if (response.success) {
          commit(types.GET_CUSTOMER_HISTORY_BUSINESS, {data: response.data, type: type})
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 工单导出
 * @param {Object} data
 * @param {Object} data._id 工单id集合 {$in:[]}
 */
export const exportBusiness = ({commit}, data) => {
  return business.exportBusiness(data)
    .then(
      response => {
        if (response.success) {
          commit(gtypes.SET_FILEDOWNLOAD, {path: response.path, isSession: true})
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const setFollowedAgents = ({commit}, data) => {
  return business.setFollowedAgents(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

export const changeBusinessRelated = ({commit}, data) => {
  return business.changeBusinessRelated(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const queryQuickSearchList = ({commit}, data) => {
  return business.queryQuickSearchList(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const queryQuickSearchListAll = ({commit}, data) => {
  return business.queryQuickSearchListAll(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const queryQuickSearchById = ({commit}, data) => {
  return business.queryQuickSearchById(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const removeQuickSearch = ({commit}, data) => {
  return business.removeQuickSearch(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const updateQuickSearch = ({commit}, data) => {
  return business.updateQuickSearch(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const setDefaultQuickSearch = ({commit}, data) => {
  return business.setDefaultQuickSearch(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const addQuickSearch = ({commit}, data) => {
  return business.addQuickSearch(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const addExportTask = ({commit}, data) => {
  return business.addExportTask(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const deleteExportTask = ({commit}, data) => {
  return business.deleteExportTask(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const getExportTaskList = ({commit}, data) => {
  return business.getExportTaskList(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const reExportTask = ({commit}, data) => {
  return business.reExportTask(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

let processBusinessData = function ({commit, rootState}, data) {
  if (data.shortCut) {
    delete data.shortCut
  }
  let p1 = getCache({commit, state: rootState}, {type: 'businessFlowField'})
  let p2 = getCache({commit, state: rootState}, {type: 'options'})
  let p3 = getCache({commit, state: rootState}, {type: 'custTmpls'})
  return Promise.all([p1, p2, p3]).then(([res1, res2, res3]) => {
    if (data.actionFields) {
      data.actionFields = addFieldDefault(data.actionFields, res2, res3)
    }
    data = addFieldDefault(data, res2, res3)
    return data
  })
}
let addFieldDefault = function (data, options, custTmpls) {
  Object.keys(data).forEach((key) => {
    let searchKey = key
    if (key.indexOf('_') !== -1) {
      searchKey = key.split('_')[0]
    }
    let field = getCacheByKey('businessFlowField', '_id', searchKey) || {}
    // 非单选，多选，下拉框不需要取字典
    if (field.type !== 'checkbox' && field.type !== 'radio' && field.type !== 'dropdown' && field.type !== 'dropdownTree') {
      return
    }
    let dic = getDicFromField(field, custTmpls, options)
    if (dic) {
      let options = []
      getAllDicOptions(dic, options)
      if (typeof data[key] === 'object') {
        if (key.indexOf('_default') < 0) {
          let defaultValue = []
          for (let m = 0; m < data[key].length; m++) {
            let keyItem = data[key][m]
            for (let i = 0; i < options.length; i++) {
              let optionItem = options[i]
              if (optionItem.key === keyItem) {
                defaultValue.push(optionItem.name)
                break
              }
            }
          }
          data[key + '_default'] = defaultValue
        }
      } else {
      // 解决导出bug， data[key]为空时，覆盖data[key + '_default']页为空
        if (!data[key]) {
          data[key + '_default'] = ''
          return
        }
        for (let i = 0; i < options.length; i++) {
          let optionItem = options[i]
          if (optionItem.key === data[key]) {
            data[key + '_default'] = optionItem.name
            break
          }
          if (i === options.length - 1 && data[key]) {
            // 收集错误，最后一个都没匹配到时执行
            let selectId = data[key]
            try {
              const error = {
                env: {
                  browser: {name: 'Chrome', version: '67.0.3396.99'},
                  os: 'Mac',
                  userAgent: 'Mozilla/5.0'
                },
                extra: {
                  componentName: '工单导出乱码'
                },
                errorType: 'TypeError',
                message: '工单导出乱码',
                referrer: 'http://kf.com/customer',
                stacktrace: {
                  frames: []
                },
                trimHeadFrames: 1,
                url: '',
                exception: {
                  values: [{
                    type: 'TypeError',
                    value: '所选字典field.dic：' + field.dic +
                    ',字段  field._id:  ' + key +
                    ',字段selectId :  ' + selectId +
                    ',工单类型 data.flow:  ' + data.flow +
                    ',工单id data._id:  ' + data._id,
                    stacktrace: {
                      frames: []
                    }
                  }]
                }
              }
              let req = {
                data: error,
                action: 'app.collect.collectVueErrorInfo'
              }
              http.fetch(req, 'post')
                .then((res) => {
                })
                .catch(err => {
                  console.error(err)
                })
            } catch (err) {
              console.log(err)
            }
          }
        }
      }
    }
  })
  return data
}
let getAllDicOptions = function (dic, result) {
  let options = dic.options || []
  for (let i = 0; i < options.length; i++) {
    let optionItem = options[i]
    result.push({key: optionItem.key, name: optionItem.name})
    let nextOptions = optionItem.options || []
    if (nextOptions.length !== 0) {
      getAllDicOptions(optionItem, result)
    }
  }
}
// 处理返回的工单数据
let businessData = ({commit, rootState, dispatch}, data) => {
  return getCache({commit, state: rootState}, {type: 'businessFlow', id: data.flow}).then((businessFlow) => {
    let isStartStep = false
    businessFlow = businessFlow || {}
    let steps = businessFlow.steps || []
    // 获取是否为开始步骤
    steps.some((item) => {
      if (item._id === data.step && item.isBegin) {
        isStartStep = true
        return true
      }
    })
    data.isStartStep = isStartStep
    return data
  })
}
export const getBusinessFlow = ({commit, dispatch}) => {
  return dispatch('getCache', {type: 'businessFlow'}).then((flows) => {
    commit(types.SET_BUSINESS_FLOWS, flows)
  })
}
export const addConfigBusinessBackInfo = ({commit}, data) => {
  return business.addConfigBusinessBackInfo(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const queryConfigBusinessById = ({commit}, data) => {
  return business.queryConfigBusinessById(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const batchAssign = ({commit}, data) => {
  return business.batchAssign(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 批量领取
 * @param {Object} data
 * @param {Array} data.ids 所选工单的id
 * @param {Number} data.total 所选工单的个数
 * @param {Object} data.condition 所选工单的条件(ids，condition 二个只传其中一个)
 */
export const batchClaim = ({commit}, data) => {
  return business.batchClaim(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
    })
}
/**
 * 批量处理工单
 * @param {Object} data
 * @param {Array} data.ids 所选工单的id
 * @param {Number} data.total 所选工单的个数
 * @param {Object} data.condition 所选工单的条件(ids，condition 二个只传其中一个)
 * @param {Object} data.data 批处理内容
 */
export const batchExecute = ({commit, rootState}, data) => {
  let submit = data
  return processBusinessData({commit, rootState}, data.data).then((res) => {
    submit.data = res
    return business.batchExecute(submit)
      .then(
        response => {
          return response
        }
      ).catch(() => {
      })
  })
}
/**
 * 批量回退工单
 * @param {Object} data
 * @param {Array} data.ids 所选工单的id
 * @param {Number} data.total 所选工单的个数
 * @param {Object} data.condition 所选工单的条件(ids，condition 二个只传其中一个)
 * @param {Object} data.data 回退工单内容
 */
export const batchBack = ({commit}, data) => {
  return business.batchBack(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
    })
}
/**
 * 设置工单稍后处理
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {Boolean} data.laterProcess 稍后处理
 */
export const setBusLaterProcess = ({commit}, data) => {
  return business.setBusLaterProcess(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
    })
}
/**
 * 变更工单优先级
 * @param {Object} data
 * @param {String} data._id 工单id
 * @param {String} data.priority 优先级
 */
export const changeBusinessPriority = ({commit}, data) => {
  return business.changeBusinessPriority(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
    })
}

// 催办
export const addUrgeContent = ({commit}, data) => {
  return business.addUrgeContent(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
    })
}
